package gl.android.biyiqing.competent;

import gl.android.biyiqing.api.API;
import gl.android.biyiqing.event.EventGreet;
import gl.common.AjaxCallBackProxy;
import gl.common.BaseControl;
import gl.common.UserManger;
import gl.uitls.GsonUtils;
import gl.uitls.Tip;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.huewu.pla.lib.internal.PLA_AdapterView;

import de.greenrobot.event.EventBus;

public class OnGreeItemClickListener implements OnItemClickListener,
		com.huewu.pla.lib.internal.PLA_AdapterView.OnItemClickListener {

	private String jsonArrayData;
	private Object[] pars;
	private String tuserid;

	public OnGreeItemClickListener(String jsonArrayData, String tuserid) {
		this.tuserid = tuserid;
		this.jsonArrayData = jsonArrayData;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		goUserInfoActivity(arg2);
	}

	private String NOTFOUND = "打招呼成功";
	private String ERR = "打招呼失败";

	private void goUserInfoActivity(int arg2) {
		try {
			List<HashMap<String, String>> map = GsonUtils
					.JSON2MapArrayList(new JSONObject(jsonArrayData)
							.getJSONArray("data"));
			String greetid = map.get(arg2).get("greetid");
			pars = new String[] { UserManger.getInstance().userid, tuserid, greetid };
			BaseControl.get(API.URL
					+ "TakeHibox?fuserid=%s&tuserid=%s&greetid=%s",
					new AjaxCallBackProxy() {

						@Override
						public void onSuccess(String t) {
							super.onSuccess(t);
							try {
								if ("1".equals(new JSONObject(t)
										.getString("msg"))) {
									Tip.show(NOTFOUND);
									EventBus.getDefault().post(new EventGreet());
									return;
								}
								if ("0".equals(new JSONObject(t)
								.getString("msg"))) {
									Tip.show(ERR);
									return;
								}
							} catch (Exception e) {
								e.printStackTrace();
								onFailure(e, 0, e.getMessage());
							}
						}

						@Override
						public void onFailure(Throwable t, int errorNo,
								String strMsg) {
							super.onFailure(t, errorNo, strMsg);
							Tip.show(ERR);
						}
					}, pars);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onItemClick(PLA_AdapterView<?> parent, View view, int position,
			long id) {
		goUserInfoActivity(position);
	}


}
